package cn.com.callback

import cn.com.elite.EliteBean
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import com.alibaba.fastjson.JSON;
import com.appletree.caizhi.dto.request.StaffClientBatchAddRequest;
import com.appletree.caizhi.dto.request.MyRequest;
import com.appletree.caizhi.dto.request.StaffClientBatchAddVo;
import com.appletree.caizhi.dto.response.ExternalResponse;
import com.tenwit.sdk.Enums.ProcessDataEnum;
import com.tenwit.sdk.client.OpenClient;
import com.tenwit.sdk.request.CommonRequest;
import com.tenwit.sdk.response.CommonResponse;
import org.junit.jupiter.api.Test;

import org.json.JSONObject
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.com.kh.getProperty;

/**
 *
 * @Title: apiSyncAddQW
 * @Description:系统API接口开发Demo，企微批量申请添加客户
 * @author: chieh
 * @date 2021-07-13 23:58:55
 *
 */

public class apiSyncAddQW implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSyncAddQW.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        String outData = "";
        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        // 入参验证
        if (inData == null) {
            outData = "{\"code\":\"-1\",\"errmsg\":\"企微申请添加客户参数为空\",\"errcode\":[]}";
        } else {
            try {
                //业务逻辑部分
                //解析Json
                JSONObject inObject = new JSONObject(inData);
                log.debug("处理前的Json：" + inObject.toString());
                def userid = GetJV(inObject, "userid");//服务顾问id
                def custname = GetJV(inObject, "custname");//客户名称
                def custmobile = GetJV(inObject, "custmobile");//客户号码
                def hshno = GetJV(inObject, "hshno");//华盛号
                def description = GetJV(inObject, "description");//备注

                log.debug("解析信息-" + "userid: " + userid+ "custname: " + custname+ "custmobile: " + custmobile+ "hshno: " + hshno+ "description: " + description);

                String url = getProperty.get("QW.URL");
                log.debug("url:"+url);
                String urlname = getProperty.get("QW.URLNAME");
                log.debug("urlname:"+urlname);
                String appId = getProperty.get("QW.APPID");
                log.debug("appId:"+appId);
                String privateKeyIsv = getProperty.get("QW.KEYISV");
                log.debug("privateKeyIsv:"+privateKeyIsv);

                /**
                 * 开放平台提供的公钥
                 * 前往SOP-ADMIN，ISV管理--秘钥管理，生成平台提供的公私钥，然后把【平台公钥】放到这里
                 */
                String publicKeyPlatform = getProperty.get("QW.KEYFORM");
                log.debug("publicKeyPlatform:"+publicKeyPlatform);

                OpenClient client = new OpenClient(url, appId, privateKeyIsv, publicKeyPlatform, ProcessDataEnum.RSA2);

                // 创建请求对象
                MyRequest requestQW = new MyRequest()

                String CorpId = getProperty.get("QW.CORPID");
                log.debug("CorpId:"+CorpId);
                // 请求参数
                StaffClientBatchAddRequest bizModel = new StaffClientBatchAddRequest();
                bizModel.setCorpId(CorpId);// 企业微信机构号
                //bizModel.setStaffUserId("yiwen"); //测试服务顾问ID
                bizModel.setStaffUserId(userid);

                List<StaffClientBatchAddVo> batchAddList = new ArrayList<>();
                StaffClientBatchAddVo batchAddVo = new StaffClientBatchAddVo();
                batchAddVo.setClientName(custname);//客户名称
                batchAddVo.setClientPhone(custmobile);//客户号码
                batchAddVo.setClientNumber(hshno);//华盛号
                batchAddVo.setClientDescription(description);//备注
                batchAddList.add(batchAddVo);

                bizModel.setBatchAddList(batchAddList);

                requestQW.setBizModel(bizModel).setCorpId(CorpId).setMethod("external.staffClient.batchAdd");

                // 发送请求
                ExternalResponse responseQW = client.execute(requestQW);
                outData = JSON.toJSONString(responseQW);
                log.debug(String.format("response:%s", outData));

            } catch (Exception e) {
                log.error("", e);
                outData = "{\"code\":\"-1\",\"errmsg\":\"企微添加客户申请处理失败(" + e.getMessage() + ")\",\"errcode\":[]}";
            }

        }

        return outData;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}